package com.bt.framework.weights

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.Animation
import android.view.animation.CycleInterpolator
import android.view.animation.TranslateAnimation
import androidx.appcompat.widget.AppCompatEditText
import com.bt.framework.R

@SuppressLint("UseCompatLoadingForDrawables")
class ClearEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.editTextStyle
) : AppCompatEditText(context, attrs, defStyleAttr), View.OnFocusChangeListener, TextWatcher {

    // 清除按钮的引用
    private var mClearDrawable: Drawable? = null

    //控件是否有焦点
    private var mHasFocus = false

    init {
        mClearDrawable = compoundDrawables[2]
        if (mClearDrawable == null) {
            mClearDrawable = context.getDrawable(R.mipmap.ic_delete_gray)
        }
        mClearDrawable?.setBounds(
            0,
            0,
            mClearDrawable?.intrinsicWidth ?: 0,
            mClearDrawable?.intrinsicHeight ?: 0
        )
        // 默认设置隐藏图标
        setClearIconVisible(false)
        // 设置焦点改变的监听
        onFocusChangeListener = this
        // 设置输入框里面内容发生改变的监听
        addTextChangedListener(this)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_UP) {
            if (compoundDrawables[2] != null) {
                val touchAble =
                    event.x > width - totalPaddingRight && event.x < width - paddingRight
                if (touchAble) {
                    this.setText("")
                }
            }
        }
        return super.onTouchEvent(event)
    }

    override fun beforeTextChanged(
        s: CharSequence?,
        start: Int,
        count: Int,
        after: Int
    ) {

    }

    /**
     * 当输入框里面内容发生变化的时候回调的方法
     */
    override fun onTextChanged(
        s: CharSequence?,
        start: Int,
        before: Int,
        count: Int
    ) {
        if (mHasFocus) {
            ////获取焦点设置回之前的图标
            mClearDrawable = context.getDrawable(R.mipmap.ic_delete_gray)
            mClearDrawable?.setBounds(
                0,
                0,
                mClearDrawable?.intrinsicWidth ?: 0,
                mClearDrawable?.intrinsicHeight ?: 0
            )
            setClearIconVisible(s.toString().isNotEmpty())
        }
    }

    override fun afterTextChanged(s: Editable?) {

    }

    /**
     * 当ClearEditText焦点发生变化的时候，判断里面字符串长度设置清除图标的显示与隐藏
     *
     * @param v
     * @param hasFocus
     */
    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        mHasFocus = hasFocus
        setClearIconVisible(hasFocus && text!!.isNotEmpty())
    }

    /**
     * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     * @param visible
     */
    fun setClearIconVisible(visible: Boolean) {
        //判断是否输入了内容,如果输入了内容我们就把弹窗关闭
        val right = if (visible) mClearDrawable else null
        setCompoundDrawables(
            compoundDrawables[0],
            compoundDrawables[1],
            right,
            compoundDrawables[3]
        )
    }

    /**
     * 设置晃动动画
     */
    fun setShakeAnimation() {
        startAnimation(shakeAnimation(5))
    }

    /**
     * 晃动动画
     *
     * @param counts 1秒晃动多少下
     * @return
     */
    private fun shakeAnimation(counts: Int): Animation {
        return TranslateAnimation(
            0f,
            10f,
            0f,
            0f
        ).apply {
            duration = 100
            interpolator = CycleInterpolator(counts.toFloat())
        }
    }
}